#include <stdio.h>
#include <mpi.h>

int main(int argc, char** argv) {
    int rank, size, tag = 1;
    int senddata, recvdata;
    MPI_Status status;
    int ierr;

    // 初始化MPI环境
    ierr = MPI_Init(&argc, &argv);
    if (ierr != MPI_SUCCESS) {
        fprintf(stderr, "MPI_Init failed\n");
        return 1;
    }

    // 获取当前进程rank和总进程数
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    if (rank == 0) {
        senddata = 999;
        // 从rank0向rank1发送一个整型数据
        ierr = MPI_Send(&senddata, 1, MPI_INT, rank + 1, tag, MPI_COMM_WORLD);
        if (ierr != MPI_SUCCESS) {
            fprintf(stderr, "Rank %d: MPI_Send failed\n", rank);
        }
        printf("Process %d send %d to Process %d\n", rank, senddata, rank + 1);
    } 
    else if (rank == 1) {
        // rank1从rank0接收一个整型数据
        ierr = MPI_Recv(&recvdata, 1, MPI_INT, rank - 1, tag, MPI_COMM_WORLD, &status);
        if (ierr != MPI_SUCCESS) {
            fprintf(stderr, "Rank %d: MPI_Recv failed\n", rank);
        }
        printf("Process %d receive %d from Process %d\n", rank, recvdata, rank - 1);
        printf("Process %d receive %d from Process %d (status source)\n", 
               rank, recvdata, status.MPI_SOURCE);
    }

    // 确保所有进程都执行到这一步
    MPI_Barrier(MPI_COMM_WORLD);

    // 终止MPI环境
    MPI_Finalize();
    return 0;
}